<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    //获取项目路径，并设置进"app_path"
    pageContext.setAttribute("app_path", request.getContextPath());
%>

<html>
<head>
    <title>用户增删改查页面</title>
    <!-- 使用EL表达式(${app_path})查出项目路径 -->
    <!-- jquery 核心 JavaScript 文件 -->
    <script src="${app_path}/static/js/jquery-3.5.1.min.js"></script>
    <!-- Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="${app_path}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <!-- Bootstrap 核心 JavaScript 文件 -->
    <script src="${app_path}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <!-- Bootstrap alert 扩展 JavaScript 文件 -->
    <script src="${app_path}/static/bootstrap-alert-extend/bootstrap-alert-extend.js"></script>
</head>
<script type="text/javascript">
    //定义一些全局变量
<<<<<<< HEAD
    let totalRecords;
    let errInputClass = "has-error";
=======
    //let totalRecords;
    //let errInputClass = "has-error";
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9

    //加载页面后进行的操作
    $(function () {
        //发送跳转请求到用户表第1页
        to_page(1);
        //绑定按钮点击事件
        bindOnEvent();
    })

    //该方法用于跳转到页面并查询
    function to_page(pn) {
        $.ajax({
            url: "http://localhost:9002/user-curd/users",//非Rest
            data: "pn=" + pn,
            type: "get",
            <%--url: "${app_path}/user-curd/users/"+pn,//伪Rest--%>
            <%--type: "GET",--%>
            //请求成功后的回调函数
            //result是请求成功后返回的Json结果
            success: function (result) {
                // 构建用户表
                build_user_table(result);
                // 构建构建页数信息条
                build_page_info(result);
                // 构建分页导航条
                build_user_nav(result);
            }
        });
    }

    //该方法用于构建用户数据表
    function build_user_table(result) {
        let $userTable = $("#user_curd_table tbody");
        $userTable.empty();//添加前需要先清空

        let userList = result.dataMap.pageInfo.list;

        //Jquery里的$.each()遍历中，index代表当前遍历的索引，item代表当前遍历的数据
        $.each(userList, function (index, item) {
            // showMsg = showMsg + index+":"+ item.id+":"+item.username+"\n";
            let $userIdTd = $("<td></td>").append(item.id);//创建id格并加入id数据
<<<<<<< HEAD
            let $usernameTd = $("<td></td>").append(item.username);//创建用户名格并加入用户名数据
=======
            let $roleNameTd = $("<td></td>").append(item.username);//创建用户名格并加入用户名数据
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
            let $passwordTd = $("<td></td>").append(item.password);//创建密码格并加入密码数据

            let $emailTd = $("<td></td>").append(item.email);//创建邮箱格并加入邮箱数据
            let $updateBtn = $("<button class=\"btn btn-primary btn-sm\">修改</button>");
            $updateBtn.click(function () {//给修改按钮设置点击事件
                $("#update_user_modal").modal({//弹出模态框
                    backdrop: "static"
                });
            });
            let $deleteBtn = $("<button class=\"btn btn-danger btn-sm\">删除</button>");
            let $operationTd = $("<td></td>").append($updateBtn).append($deleteBtn);//创建操作格并加入操作按钮

            let $userTr = $("<tr></tr>")//创建用户数据行并加入各种数据格子
                .append($userIdTd)
<<<<<<< HEAD
                .append($usernameTd)
=======
                .append($roleNameTd)
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
                .append($passwordTd)
                .append($emailTd)
                .append($operationTd);

            $userTable.append($userTr);//将数据行加入表格中
        })
    }

    //该方法用于构建页数信息条
    function build_page_info(result) {
        let $pageInfo = $("#page_info");
        $pageInfo.empty();//先清空"页数信息条"里的信息

        let pageNum = result.dataMap.pageInfo.pageNum;//当前页码
        let pageSize = result.dataMap.pageInfo.pageSize;//页容量
        let pages = result.dataMap.pageInfo.pages;//总页数
        let total = result.dataMap.pageInfo.total;//总数据量
<<<<<<< HEAD
        totalRecords = total;
=======
        //totalRecords = total;
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9

        let $pageInfoP = $("<span></span>").append(
            "当前页:" + pageNum + "&nbsp;&nbsp;" +
            "页显示量:" + pageSize + "&nbsp;&nbsp;" +
            "总页数:" + pages + "&nbsp;&nbsp;" +
            "总数据量:" + total);

        $pageInfo.append($pageInfoP);//再往"页数信息条"里添加信息
    }

    //该方法用于构建分页导航条
    function build_user_nav(result) {
        let $navUl = $("#page_nav");//找到需要被添加的导航栏对象
        $navUl.empty();//添加前需要先清空

        let pageNum = result.dataMap.pageInfo.pageNum;//当前页码
        let pageSize = result.dataMap.pageInfo.pageSize;//页容量
        let pages = result.dataMap.pageInfo.pages;//总页数
        let total = result.dataMap.pageInfo.total;//总数据量
        let isFirstPage = result.dataMap.pageInfo.isFirstPage;//是否是首页的标识
        let isLastPage = result.dataMap.pageInfo.isLastPage;//是否是尾页的标识
        let navigatepageNums = result.dataMap.pageInfo.navigatepageNums;//导航栏要显示的数字们

        let $firstPageLi = $("<li></li>").append(
            $("<a></a>").append("首页").attr("href", "#")
        );
        let $prePageLi =
            $("<li></li>").append(
                $("<a></a>").append(
                    $("<span></span>").append("&laquo;")
                ).attr("href", "#")
            );

        let $nextPageLi =
            $("<li></li>").append(
                $("<a></a>").append(
                    $("<span></span>").append("&raquo;")
                ).attr("href", "#")
            );
        let $lastPageLi = $("<li></li>").append(
            $("<a></a>").append("尾页").attr("href", "#")
        );

        //如果是首页，则有两个按钮不能点击
        if (isFirstPage) {
            $firstPageLi.addClass("disabled");//第一页li添加disabled的class
            $firstPageLi.find("a").removeAttr("href");//找到第一页li下的a标签并清除属性

            $prePageLi.addClass("disabled");//前一页li添加disabled的class
            $prePageLi.find("a").removeAttr("href");//找到前一页li下的a标签并清除href属性
        } else {
            $firstPageLi.click(function () {
                to_page(1);
            });
            $prePageLi.click(function () {
                to_page(pageNum - 1);
            });
        }

        //如果是尾页，则有两个按钮不能点击
        if (isLastPage) {
            $lastPageLi.addClass("disabled");//最后页li添加disabled的class
            $lastPageLi.find("a").removeAttr("href");//找到最后页li下的a标签并清除属性

            $nextPageLi.addClass("disabled");//后一页li添加disabled的class
            $nextPageLi.find("a").removeAttr("href");//找到后一页li下的a标签并清除href属性
        } else {
            $lastPageLi.click(function () {
                to_page(pages);
            });
            $nextPageLi.click(function () {
                to_page(pageNum + 1);
            });
        }

        //添加"首页"按钮
        $navUl.append($firstPageLi);
        //添加"上一页"按钮
        $navUl.append($prePageLi);
        //遍历添加所有要显示的页码
        $.each(navigatepageNums, function (index, item) {
            let $numLi = $("<li></li>").append(
                $("<a></a>").append(item).attr("href", "#")
            );
            //如果目前的页码真的与遍历页码相等
            if (pageNum == item) {
                $numLi.addClass("active");
                $numLi.empty();//清除里面能点击的a标签
                $numLi.append(
                    $("<span></span>").append(item).append(
                        $("<span></span>").addClass("sr-only")
                    )
                );
            }
            //设置显示的页码格子的点击事件
            $numLi.click(function () {
                to_page(item);
            });

            $navUl.append($numLi);//将每一个要显示的页码加入导航栏中
        });
        //添加"下一页"按钮
        $navUl.append($nextPageLi);
        //添加"尾页"按钮
        $navUl.append($lastPageLi);
    }

    /**
     * 该方法用于清除错误提示
     */
    function clearUserForm() {
        let $username_add_input = $("#username_add_input");
        let $password_add_input = $("#password_add_input");
        let $email_add_input = $("#email_add_input");
        //移除所有的错误提示样式
<<<<<<< HEAD
        $username_add_input.parent().removeClass(errInputClass);
        $username_add_input.next("span").empty();
        $password_add_input.parent().removeClass(errInputClass);
        $password_add_input.next("span").empty();
        $email_add_input.parent().removeClass(errInputClass);
=======
        $username_add_input.parent().removeClass("has-error");
        $username_add_input.next("span").empty();
        $password_add_input.parent().removeClass("has-error");
        $password_add_input.next("span").empty();
        $email_add_input.parent().removeClass("has-error");
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
        $email_add_input.next("span").empty();
    }


    /**
     * 该方法用于检查用户添加表格
     */
    function checkUserForm() {
        let $username_add_input = $("#username_add_input");
        let $password_add_input = $("#password_add_input");
        let $email_add_input = $("#email_add_input");

        let username_input = $username_add_input.val();
        let username_reg = /^([A-Za-z0-9_-]){6,20}$/;
        let username_hint = "用户名必须为6-20位的英文字符或数字!";
        let password_input = $password_add_input.val();
        let password_reg = /^[A-Za-z0-9]{6,20}$/;
        let password_hint = "密码必须为6-20位的英文字符或数字!";
        let email_input = $email_add_input.val();
        let email_reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        let email_hint = "邮箱格式错误!";

        let result = true;

        //开始时移除所有的错误提示样式
        clearUserForm();

        if (!username_reg.test(username_input)) {//若不匹配，显示提示
<<<<<<< HEAD
            $username_add_input.parent().addClass(errInputClass);
=======
            $username_add_input.parent().addClass("has-error");
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
            $username_add_input.next("span").append(username_hint);
            result = false;
        } else {
            result = result & true;
        }
        if (!password_reg.test(password_input)) {//若不匹配，显示提示
<<<<<<< HEAD
            $password_add_input.parent().addClass(errInputClass);
=======
            $password_add_input.parent().addClass("has-error");
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
            $password_add_input.next("span").append(password_hint);
            result = false;
        } else {
            result = result & true;
        }
        if (!email_reg.test(email_input)) {//若不匹配，显示提示
<<<<<<< HEAD
            $email_add_input.parent().addClass(errInputClass);
=======
            $email_add_input.parent().addClass("has-error");
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
            $email_add_input.next("span").append(email_hint);
            result = false;
        } else {
            result = result & true;
        }

        return result;
    }


    function showErrorToFrom(result){
        //先清除错误提示
        clearUserForm();

        let $username_add_input = $("#username_add_input");
        let $password_add_input = $("#password_add_input");
        let $email_add_input = $("#email_add_input");

        if (result.dataMap.fieldErrors.username != undefined) {//若不匹配，显示提示
<<<<<<< HEAD
            $username_add_input.parent().addClass(errInputClass);
            $username_add_input.next("span").append(result.dataMap.fieldErrors.username);
        }
        if (result.dataMap.fieldErrors.password != undefined) {//若不匹配，显示提示
            $password_add_input.parent().addClass(errInputClass);
            $password_add_input.next("span").append(result.dataMap.fieldErrors.password);
        }
        if (result.dataMap.fieldErrors.email != undefined) {//若不匹配，显示提示
            $email_add_input.parent().addClass(errInputClass);
=======
            $username_add_input.parent().addClass("has-error");
            $username_add_input.next("span").append(result.dataMap.fieldErrors.username);
        }
        if (result.dataMap.fieldErrors.password != undefined) {//若不匹配，显示提示
            $password_add_input.parent().addClass("has-error");
            $password_add_input.next("span").append(result.dataMap.fieldErrors.password);
        }
        if (result.dataMap.fieldErrors.email != undefined) {//若不匹配，显示提示
            $email_add_input.parent().addClass("has-error");
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
            $email_add_input.next("span").append(result.dataMap.fieldErrors.email);
        }
    }


    /**
     * 该方法用于给控件绑定事件
     */
    function bindOnEvent() {
        //绑定弹出模态框的点击事件
        $("#add_user_btn").click(function () {
            //调用html元素的清除表单数据方法
            $("#add_user_form")[0].reset();
            //清除错误提示
            clearUserForm();
            //弹出模态框
            $("#addUserModal").modal({
                backdrop: "static"
            });
        })

        //绑定删除按钮的点击事件
        $("#delete_user_btn").click(function () {
            let deleteData = [2,125019,125020];

            $.ajax({
                url: "http://localhost:9002/user-curd/users",
                data: "idList="+deleteData,
                type: "DELETE",
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    if (result.code == 200){
                        alertUtil.message(result.msg,"success");
                    }else {
                        alertUtil.message(result.msg,"danger");
                    }
                    //跳转到第一页
                    to_page(1);
                }
            });
        })

        //给各输入框添加焦点模糊事件
        let $username_add_input = $("#username_add_input");
        let $password_add_input = $("#password_add_input");
        let $email_add_input = $("#email_add_input");
        $username_add_input.bind("input propertychange", function () {
            checkUserForm();
        });
        $password_add_input.bind("input propertychange", function () {
            checkUserForm();
        });
        $email_add_input.bind("input propertychange", function () {
            checkUserForm();
        });

        //绑定测试的按钮的点击事件
        $("#test1_btn").click(function () {
            alertUtil.message("我是弹出框的显示的结果"); // 直接调用commonUtil对象的message方法
        });

        //绑定添加用户的按钮的点击事件
        $("#user_add_confirm").click(function () {
            //使用jq自带的序列化方法直接将表格中的数据取出
            let userData = $("#add_user_form").serialize();
            // alert(userData);

            if (checkUserForm()) {//如果检查表格成功checkUserForm()
                $.ajax({
                    url: "http://localhost:9002/user-curd/users",
                    data: userData,
                    type: "POST",
                    //请求成功后的回调函数
                    //result是请求成功后返回的Json结果
                    success: function (result) {
                        //判断保存的状态，200为成功，400为失败
                        if (result.code == 200) {
                            //关闭模态框
                            $("#addUserModal").modal("hide");
                            //来到最后一页
<<<<<<< HEAD
                            to_page(totalRecords);
=======
                            to_page(9999);
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
                            //提示保存成功
                            alertUtil.message(result.msg,"success");
                        } else {
                            console.log(result);

                            // 查看是否有后端回传的详细错误提示
                            if (result.dataMap.fieldErrors != undefined){
                                //将失败的提示显示到模态框上
                                showErrorToFrom(result);
                            }else{
                                // 关闭模态框
                                $("#addUserModal").modal("hide");
                                //提示保存失败
                                alertUtil.message(result.msg,"danger");
                            }
                        }
                    }
                });
            }
        })
    }

</script>

<body>

<!-- 该模态框用于更新用户 -->
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <%--            <div id="show_msg_div" class="alert alert-danger alert-dismissible" role="alert">--%>
            <%--                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>--%>
            <%--                <strong>错误!</strong> 添加员工失败！--%>
            <%--            </div>--%>
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <!-- 模态框标题 -->
                <h4 class="modal-title" >用户修改</h4>
            </div>
            <div class="modal-body">
                <form id="update_user_form" class="form-horizontal">
                    <div class="form-group" style="display:none" >
                        <label class="col-sm-2 control-label">ID</label>
                        <div class="col-sm-10">
                            <input type="text" name="id" class="form-control" id="id_update_input" disabled>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">用户名</label>
                        <div class="col-sm-10">
                            <!-- placeholder是显示输入提示的属性 -->
                            <!-- name属性的值与实体类的属性名相同是为了能自动进行类对象的实例化 -->
                            <input type="text" name="username" class="form-control" id="username_update_input"
                                   placeholder="用户名(6-20位的英文字符或数字)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">昵称</label>
                        <div class="col-sm-10">
                            <input type="text" name="nickname" class="form-control" id="nickname_update_input"
                                   placeholder="昵称(4-10位的字符)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input type="password" name="password" class="form-control" id="password_update_input"
                                   placeholder="密码(6-20位的英文字符或数字)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="email_update_input"
                                   placeholder="邮箱(example@xx.com)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="user_update_cancel" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="user_update_confirm" class="btn btn-primary">修改</button>
            </div>
        </div>
    </div>
</div>

<!-- 该模态框用于添加员工 -->
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <%--            <div id="show_msg_div" class="alert alert-danger alert-dismissible" role="alert">--%>
            <%--                <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>--%>
            <%--                <strong>错误!</strong> 添加员工失败！--%>
            <%--            </div>--%>
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <!-- 模态框标题 -->
                <h4 class="modal-title" id="myModalLabel">用户添加</h4>
            </div>
            <div class="modal-body">
                <form id="add_user_form" class="form-horizontal">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">用户名</label>
                        <div class="col-sm-10">
                            <!-- placeholder是显示输入提示的属性 -->
                            <!-- name属性的值与实体类的属性名相同是为了能自动进行类对象的实例化 -->
                            <input type="text" name="username" class="form-control" id="username_add_input"
                                   placeholder="用户名(6-20位的英文字符或数字)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">昵称</label>
                        <div class="col-sm-10">
<<<<<<< HEAD
<<<<<<< HEAD
=======
                            <!-- placeholder是显示输入提示的属性 -->
                            <!-- name属性的值与实体类的属性名相同是为了能自动进行类对象的实例化 -->
>>>>>>> c34598f1021817b3770e4d5b76319f17355396a3
=======
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9
                            <input type="text" name="nickname" class="form-control" id="nickname_add_input"
                                   placeholder="昵称(4-10位的字符)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">密码</label>
                        <div class="col-sm-10">
                            <input type="password" name="password" class="form-control" id="password_add_input"
                                   placeholder="密码(6-20位的英文字符或数字)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="email" name="email" class="form-control" id="email_add_input"
                                   placeholder="邮箱(example@xx.com)">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <%--                    <div class="form-group">--%>
                    <%--                        <div class="col-sm-offset-2 col-sm-10">--%>
                    <%--                            <button type="submit" class="btn btn-default">Sign in</button>--%>
                    <%--                        </div>--%>
                    <%--                    </div>--%>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="user_add_cancel" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="user_add_confirm" class="btn btn-primary">确认</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <%-- 该行用于显示 --%>
    <div class="row">
        <div class="col-md-6">
            <h1>用户增删改查测试</h1>
        </div>
    </div>
    <%-- 该行用于显示测试按钮 --%>
    <%-- 该行用于显示增加和删除按钮 --%>
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <button id="test1_btn" class="btn btn-info">测试1按钮</button>
            <button id="test2_btn" class="btn btn-danger">测试2按钮</button>
        </div>
        <div class="col-md-4">
            <button id="add_user_btn" class="btn btn-info">增加用户</button>
            <button id="delete_user_btn" class="btn btn-danger">删除用户</button>
        </div>
    </div>
    <%-- 该行用于显示用户信息的表格 --%>
    <div class="row">
        <div class="col-md-12">
            <table id="user_curd_table" class="table table-striped table-hover">
                <thead>
                <tr>
                    <th>id</th>
                    <th>用户名</th>
                    <th>密码</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>

        </div>
    </div>
    <%-- 该行用于显示分页信息 --%>
    <div class="row">
        <%-- 该列用于显示页数信息 --%>
        <div id="page_info" class="col-md-6">
            <p>当前页:&nbsp;&nbsp;页显示量:&nbsp;&nbsp;总页数:&nbsp;&nbsp;总数据量:</p>
        </div>
        <%-- 该列用于显示分页导航条 --%>
        <div class="col-md-6">
            <nav aria-label="Page navigation">
<<<<<<< HEAD
                <ul id="page_nav" class="pagination">
=======
                <ul id="page_nav" class="pager">
>>>>>>> 6b30610544899921d6826fbc9ab63b7d3c4c91e9

                </ul>
            </nav>
        </div>
    </div>


</div>


</body>
</html>
